extends CharacterBody2D


const SPEED = 300.0
const JUMP_VELOCITY = -400.0

var jumping = false

func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta
	
	if jumping and is_on_floor():
		land()
	
	# Handle jump.
	if Input.is_action_just_pressed("ui_accept") and is_on_floor() and not jumping:
		jump()

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var direction := Input.get_axis("ui_left", "ui_right")
	if direction:
		velocity.x = direction * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		
	if self.velocity.x != 0:
		if self.velocity.x > 0:
			$AnimatedSprite2D.flip_h = true
		else:
			$AnimatedSprite2D.flip_h = false
		
		if not self.jumping:
			if not $AnimatedSprite2D.is_playing() or $AnimatedSprite2D.animation != "run":
				$AnimatedSprite2D.play("run")
	else:
		if not jumping and $AnimatedSprite2D.is_playing() and $AnimatedSprite2D.animation == "run":
			$AnimatedSprite2D.play("idle")
	
	move_and_slide()

func jump():
	self.jumping = true
	$AnimatedSprite2D.play("jump")
	self.velocity.y = JUMP_VELOCITY

func land():
	self.velocity.y = 0
	$AnimatedSprite2D.play("land")

func _on_animated_sprite_2d_animation_finished() -> void:
	if $AnimatedSprite2D.animation == "jump":
		$AnimatedSprite2D.play("air")
	if $AnimatedSprite2D.animation == "land":
		jumping = false
		$AnimatedSprite2D.play("idle")
